<template>
  <div class="overlay" @click.self="close">
    <div class="detail-container" v-if="postdata">
      <div class="left-panel">
        <img :src="currentImage" class="main-image" />
        <div class="image-thumbnails">
          <img
            v-for="(url, index) in postdata.imageUrls"
            :key="index"
            :src="url"
            @click="currentImage = url"
            class="thumbnail"
          />
        </div>
      </div>

      <div class="right-panel">
        <div class="author-bar">
          <img :src="postdata.authorImg" class="author-avatar" @click="router.push('/user/' + postdata.authorId)"/>
          <span class="author-name">{{ postdata.authorName }}</span>
          <div class="stats">
            <img :src="postdata.isLike ? likeActive : likeIcon" class="icon"  @click.stop="handleLike(postdata)"/>
            <span>{{ postdata.likeCount }}</span>
            <img :src="postdata.isFavorite ? favActive : favIcon" class="icon" @click.stop="handleFavorite(postdata)" />
            <span>{{ postdata.favoriteCount }}</span>
            <button v-if="postdata.isMe" @click="deletePostfunc(postdata)" class="delete">删除</button>
          </div>
        </div>

        <div class="content-scroll">
          <h2 class="title">{{ postdata.title }}</h2>
          <p class="content">{{ postdata.content }}</p>
          <div class="tags">
            <span v-for="tag in postdata.tags" :key="tag" class="tag">#{{ tag }}</span>
          </div>
          <div class="time">{{ formatTime(postdata.createTime) }}</div>

          <div class="comments">
            <!-- 评论列表和二级评论 -->
            <div
              v-for="comment in comments"
              :key="comment.id"
              class="comment"
            >
              <div class="comment-header">
                <img :src="comment.userImgUrl" class="comment-avatar" @click="router.push('/user/' + comment.userId)"/>
                <span class="username">{{ comment.userName }}</span>
                <span v-if="comment.isAuthor" class="badge">作者</span>
                <span v-if="comment.isMe" class="badge">我</span>
                <button v-if="comment.isMe" @click="deleteComment(comment)" class="delete">删除</button>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <div class="comment-footer">
                <span>{{ formatTime(comment.createTime) }}</span>
                <img :src="comment.isLike ? likeActive : likeIcon" class="icon" @click="likeCommentfunc(comment)" />
                <span>{{ comment.likeCount }}</span>
                <button class="reply-btn" @click="prepareReply(comment.id, comment.userName)">回复</button>
              </div>

              <div
                v-for="reply in comment.sonComments || []"
                :key="reply.id"
                class="reply"
              >
                <div class="comment-header">
                  <img :src="reply.userImgUrl" class="comment-avatar" />
                  <span class="username">{{ reply.userName }}</span>
                  <span v-if="reply.isAuthor" class="badge">作者</span>
                  <span v-if="reply.isMe" class="badge">我</span>
                  <button v-if="reply.isMe" @click="deleteComment(reply)" class="delete">删除</button>
                </div>
                <div class="comment-content">回复 {{ reply.replyUserName }}：{{ reply.content }}</div>
                <div class="comment-footer">
                  <span>{{ formatTime(reply.createTime) }}</span>
                  <img :src="reply.isLike ? likeActive : likeIcon" class="icon" @click="likeCommentfunc(reply)" />
                  <span>{{ reply.likeCount }}</span>
                  <button class="reply-btn" @click="prepareReply(comment.id, reply.userName)">回复</button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="reply-bar">
          <input
            v-model="replyContent"
            :placeholder="replyHint"
            class="reply-input"
          />
          <button @click="sendReply" class="send-btn" :disabled="isSendDisable">发送</button>
          <button v-if="replyTarget.replyUser" @click="clearReply" class="canel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,computed,watch   } from 'vue'
import {
  searchComment,
  likePost,
  deletePost,
  favoritePost,
  likeComment,
  deletePostComment,
  commentPost
} from '@/api/CommunityApi'
import likeIcon from '@/assets/community/like.png'
import favIcon from '@/assets/community/favorite.png'
import likeActive from '@/assets/community/liked.png'
import favActive from '@/assets/community/favorited.png'
import { ElMessage } from 'element-plus'
import router from '@/router'

const props = defineProps({
  postdata: Object
})

const emit = defineEmits(['close', 'deleted'])

const close = () => {
  emit('close')
}

const comments = ref([])
// const currentImage = ref(props.postdata.imageUrls[0])
const currentImage = ref('')
const replyContent = ref('')
const replyTarget = ref({ parentId: 0, replyUser: null })

const replyHint = computed(() =>
  replyTarget.value.replyUser ? `回复 ${replyTarget.value.replyUser}：` : '发表评论...'
)

const formatTime = (str) => str.slice(0, 16).replace('T', ' ')

const loadComments = async () => {
  if (!props.postdata?.id) return
  try {
    const res = await searchComment(props.postdata.id)
    const allComments = res.data.data || []

    // 过滤出一级评论（parentId 为 0）
    const topLevel = allComments.filter(c => c.parentId === 0)

    comments.value = topLevel
  } catch (err) {
    console.error('加载评论失败', err)
  }
}

watch(
  () => props.postdata,
  (newVal) => {
    if (newVal && newVal.id) {
      loadComments()
    }
    if (newVal && newVal.imageUrls && newVal.imageUrls.length > 0) {
      currentImage.value = newVal.imageUrls[0]
    }
  },
  { immediate: true }
)

const prepareReply = (parentId, userName) => {
  replyTarget.value = { parentId, replyUser: userName }
}

const clearReply = () => {
  replyTarget.value = { parentId: 0, replyUser: null }
}

const isSendDisable = ref(false)
const sendReply = async () => {
  isSendDisable.value = true
  const text = replyContent.value.replace(/^回复\s.*?：/, '')
  if (!text.trim()) return
  await commentPost(
    props.postdata.id,
    text,
    replyTarget.value.parentId,
    replyTarget.value.replyUser
  )
  replyContent.value = ''
  clearReply()
  loadComments()
  ElMessage.success("发布成功")
  isSendDisable.value = false
}

const deletePostfunc = async (data) => {
  await deletePost(data.id)
  ElMessage.success("删除帖子成功")
  emit('deleted')  // 发送事件
  close()
}

const deleteComment = async (data) => {
  await deletePostComment(data.id)
  ElMessage.success("删除评论成功")
  loadComments()
}

const likeCommentfunc = async (data) => {
  data.isLike = !data.isLike;
  if(data.isLike){
    data.likeCount++;
  }
  else {
    data.likeCount = data.likeCount - 1 > 0 ? data.likeCount - 1 : 0;
  }
  const res = await likeComment(data.id)
  loadComments()
}


const handleLike = async (post) =>{
  try {
    post.isLike = !post.isLike;
    if(post.isLike){
      post.likeCount++;
    }
    else {
      post.likeCount = post.likeCount - 1 > 0 ? post.likeCount - 1 : 0;
    }
    const res = await likePost(post.id)
  } catch (error) {
    console.error('数据获取失败:', error)
  }
}

const handleFavorite = async (post) =>{
  try {
    post.isFavorite = !post.isFavorite;
    if(post.isFavorite){
      post.favoriteCount++;
    }
    else {
      post.favoriteCount = post.favoriteCount - 1 > 0 ? post.favoriteCount - 1 : 0;
    }
    const res = await favoritePost(post.id)
  } catch (error) {
    console.error('数据获取失败:', error)
  }
}

onMounted(() => {
  loadComments()
})
</script>

<style scoped>
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.detail-container {
  background: white;
  width: 80vw;
  height: 80vh;
  display: flex;
  border-radius: 12px;
  overflow: hidden;
}

.left-panel {
  width: 40%;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.main-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

.image-thumbnails {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  overflow-x: auto;
}

.thumbnail {
  width: 60px;
  height: 60px;
  object-fit: cover;
  cursor: pointer;
  border: 2px solid #ccc;
  border-radius: 6px;
}

.right-panel {
  width: 60%;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.author-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 10px;
}

.author-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 1px solid #7f6748;
}

.stats {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 10px;
}

.icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.content-scroll {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.title {
  font-size: 20px;
  font-weight: bold;
}

.content {
  margin-top: 10px;
  white-space: pre-wrap;
}

.tags {
  margin-top: 10px;
}

.tag {
  color: #007bff;
  margin-right: 8px;
  cursor: pointer;
}

.time {
  text-align: right;
  margin-top: 5px;
  color: #888;
}

.comment {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.comment-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  border: 1px solid #7f6748;
}

.username {
  font-weight: bold;
}

.badge {
  background: #ffc107;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.reply-btn {
  background-color: rgba(0, 123, 255, 0.1);
  color: #007bff;
  border: none;
  font-size: 14px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}


.delete {
  margin-left: auto;
  background: #f44336; /* 红色背景 */
  color: #ffffff;      /* 白色文字 */
  border: none;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 4px;
}


.comment-content {
  margin-top: 5px;
}

.comment-footer {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 5px;
  color: #888;
}

.reply {
  margin-left: 50px;
  margin-top: 10px;
}

.reply-bar {
  display: flex;
  align-items: center;
  border-top: 1px solid #ccc;
  padding-top: 10px;
}

.reply-input {
  flex: 1;
  padding: 8px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.send-btn {
  margin-left: 10px;
  background-color: #4caf50;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.canel-btn {
  margin-left: 10px;
  background-color: #b49c3c;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>
